# https://oapi.dingtalk.com/robot/send?access_token=b902e240785566ee4737848510b7101bd57a8fd1a1acb5bcac2cf3a3d0d1ccf2

import ssl

ssl._create_default_https_context = ssl._create_unverified_context

# self.app_key = 'dingspehapjuc9orhx99'
# self.app_secret = '76Bvuj1L40frcDwfEJsUTr44P5uaFIs6IeDg7ak1mk8TsB_pwTb05VVun2KGsftb'
# self.chat_id = 'chat19a1a36454b54ba1f565e44e03c4d4d8'
# self.domain = "https://oapi.dingtalk.com"

import time
import hmac
import hashlib
import base64
import json
import urllib.parse
import urllib.request


class DingDingWebHook(object):
    def __init__(self, secret=None, url=None):
        """
        :param secret: 安全设置的加签秘钥
        :param url: 机器人没有加签的WebHook_url
        """
        if secret is not None:
            secret = secret
        else:
            secret = 'ding9hbx0koepzh1axvr'  # 加签秘钥
        if url is not None:
            url = url
        else:
            url = 'https://oapi.dingtalk.com/robot/send?access_token=b902e240785566ee4737848510b7101bd57a8fd1a1acb5bcac2cf3a3d0d1ccf2'
        # 无加密的url

        timestamp = round(time.time() * 1000)  # 时间戳
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))  # 最终签名

        self.webhook_url = url + '&timestamp={}&sign={}'.format(timestamp, sign)  # 最终url，url+时间戳+签名

    def send_meassage(self, data):
        """
        发送消息至机器人对应的群
        :param data: 发送的内容
        :return:
        """
        header = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"
        }
        send_data = json.dumps(data)  # 将字典类型数据转化为json格式
        send_data = send_data.encode("utf-8")  # 编码为UTF-8格式
        request = urllib.request.Request(url=self.webhook_url, data=send_data, headers=header)  # 发送请求

        opener = urllib.request.urlopen(request)  # 将请求发回的数据构建成为文件格式
        # print(opener.read())  # 打印返回的结果


"""
配置通用方法将批次号和执行结果传入
其他消息在说
"""


class DingDingNotice():
    def DingdingNotice(pici, result):
        my_secret = 'ding9hbx0koepzh1axvr'  # 加签秘钥
        print(pici)
        my_url = 'https://oapi.dingtalk.com/robot/send?access_token=b902e240785566ee4737848510b7101bd57a8fd1a1acb5bcac2cf3a3d0d1ccf2'
        notice = {"title": "自动化脚本执行通知",
                  "text": "# 自动化脚本执行通知 \n## 批次号:  \n> 执行结果:"},
        text = str("# 自动化脚本执行通知 \n## 批次号:  \n> 执行结果:")
        text1 = text.replace('批次号:', pici)
        url = "http://192.168.16.91:8000/#/echarts_report/pici=" + str(pici).replace("批次号", '')
        """替换执行结果"""
        text2 = text1.replace('执行结果:', '【' + result + "】,查看网址:" + url)
        notice[0]['text'] = text2
        my_data = {
            "msgtype": "markdown",
            "markdown": "%s" % notice,
            "at": {
                # "atMobiles": "%s" %mobile,
                "isAtAll": True}  # 是否@所有人
        }

        dingding = DingDingWebHook(secret=my_secret, url=my_url)
        dingding.send_meassage(my_data)
